package com.biostime.qdingding.modules.qd.promotions;

import com.biostime.qdingding.common.utils.SpringContextHolder;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.Promotion;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 报名前三返10
 * @author phil
 *
 */
public class FirstNDiscountor implements Discountor {
	
	public static final String Formula = "FirstNDiscountor";
	
	public FirstNDiscountor(){
		courseOrderService = SpringContextHolder.getBean(CourseOrderService.class);
	}
	
	private CourseOrderService courseOrderService;
	
	@Override
	public void discount(Discountable discountable) {
		if(support(discountable)){
			System.out.println("前几返几");
			
			Course course = (Course)discountable;
			Promotion promotion = course.getPromotions().get(Formula);
			
			//第一步：获取第几名选课
			int number = courseOrderService.getRank(course);
			
			//第二步：根据促销设置促销参数值
			ObjectMapper mapper = new ObjectMapper();
			FirstNDiscountor.Arg arg = null;
			try {
				arg = mapper.readValue(promotion.getArgValue(), FirstNDiscountor.Arg.class);
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
			//第三步：求出折扣价格
			if(arg!=null){
				if(number>0 && number<=arg.getN()){
					String promotionName = String.format("前三返10", arg.money);
					promotion.setMoney(arg.money);
					
					promotion.setPromotionName(promotionName);
					promotion.setPreMoney(course.getPriceNow());
					course.setPriceNow(course.getPriceNow()-arg.money);	
				}
			}
		}else{
			System.out.println("前几返几 ( Not Support )!");
		}
	}

	@Override
	public boolean support(Discountable discountable) {
		Course course = (Course)discountable;
		
		return course.getPromotions().containsKey(Formula);
	}

	/**
	 * 配置参数类
	 * @author phil
	 * @version 2015-11-20
	 */
	public static class Arg{
		
		private int n; //前几名选课
		private double money; //返回现金
		
		public int getN() {
			return n;
		}
		public void setN(int n) {
			this.n = n;
		}
		
		public double getMoney() {
			return money;
		}
		public void setMoney(double money) {
			this.money = money;
		}
	}
}
